<template>
  <BasicModal v-bind="$attrs" @register="registerModal" title="密保手机" @ok="handleSubmit" width="600px">
    <BasicForm @register="registerForm">
      <template #inputCode="{ model, field }">
        <a-input-group compact>
          <a-input class="randcode-input" v-model:value="model[field]" />
          <div class="randcode-btn">
            <img
              v-if="randCodeData.requestCodeSuccess"
              style="margin-top: 2px; max-width: initial"
              :src="randCodeData.randCodeImage"
              @click="handleChangeCheckCode"
            />
            <img v-else style="margin-top: 2px; max-width: initial" src="../../../../assets/images/checkcode.png" @click="handleChangeCheckCode" />
          </div>
        </a-input-group>
      </template>
    </BasicForm>
  </BasicModal>
</template>
<script lang="ts" setup>
  import { reactive, ref, unref, defineExpose, onMounted } from 'vue';
  import { rules } from '/@/utils/helper/validator';
  import { defHttp } from '/@/utils/http/axios';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { getCodeInfo } from '/@/api/sys/user';
  import { useGlobSetting } from '/@/hooks/setting';
  import { buildUUID } from '/@/utils/uuid';
  import { isNullOrUnDef, isEmpty } from '/@/utils/is';

  const globSetting = useGlobSetting();

  // 声明Emits
  const emit = defineEmits(['register']);
  const $message = useMessage();
  const formRef = ref();

  const formData = reactive({
    captcha: '',
    mobile: '',
    inputCode: '',
  });
  const randCodeData = reactive({
    randCodeImage: '',
    requestCodeSuccess: false,
    checkKey: '',
  });

  //表单配置
  const [registerForm, { resetFields, validate, getFieldsValue, clearValidate }] = useForm({
    schemas: [
      {
        label: '手机号码',
        field: 'mobile',
        component: 'Input',
        required: true,
        dynamicRules: ({ values }) => rules.phone(values),
      },
      // {
      //   label: '图形验证码',
      //   field: 'inputCode',
      //   component: 'Input',
      //   required: true,
      //   slot: 'inputCode',
      // },
      {
        field: 'captcha',
        component: 'InputCountDown',
        label: '短信验证码',
        required: true,
        componentProps: {
          sendCodeApi: sendCodeApi,
        },
      },
    ],
    showActionButtonGroup: false,
  });
  //表单赋值
  const [registerModal, { setModalProps, closeModal }] = useModalInner();

  function handleChangeCheckCode() {
    formData.inputCode = '';
    //randCodeData.checkKey = 1629428467008; //new Date().getTime();
    randCodeData.checkKey = buildUUID();
    getCodeInfo(randCodeData.checkKey).then((res) => {
      randCodeData.randCodeImage = res;
      randCodeData.requestCodeSuccess = true;
    });
  }

  //倒计时执行前的函数
  // async function sendCodeApi() {
  //   try {
  //     const values = getFieldsValue();
  //     if (isNullOrUnDef(values.inputCode) || isEmpty(values.inputCode)) {
  //       $message.createMessage.warning('请输入图形验证码');
  //       return false;
  //     }
  //     if (isNullOrUnDef(values.mobile) || isEmpty(values.mobile)) {
  //       $message.createMessage.warning('请输入手机号码');
  //       return false;
  //     }
  //     let params = Object.assign({ deviceId: unref(randCodeData.checkKey), inputCode: unref(values.inputCode), mobile: unref(values.mobile) });
  //     let url = '/api-uaa/validata/smsCode' + '/' + params.deviceId + '/' + params.inputCode + '/' + params.mobile;
  //     defHttp.get({ url: url }, { isTransformResponse: false }).then((res) => {
  //       if (res.success) {
  //         $message.createMessage.success('发送成功');
  //         return true;
  //       } else {
  //         $message.createMessage.warning(res.msg);
  //         handleChangeCheckCode();
  //         return false;
  //       }
  //     });
  //   } finally {
  //     return false;
  //   }
  // }

  async function sendCodeApi() {
    try {
      const values = getFieldsValue();
      if (isNullOrUnDef(values.mobile) || isEmpty(values.mobile)) {
        $message.createMessage.warning('请输入手机号码');
        return false;
      }
      let params = Object.assign({ deviceId: unref(randCodeData.checkKey), inputCode: unref(values.inputCode), mobile: unref(values.mobile) });
      let url = '/api-uaa/validata/smsCode' + '/' + params.mobile;
      defHttp.get({ url: url }, { isTransformResponse: false }).then((res) => {
        if (res.success) {
          $message.createMessage.success('发送成功');
          return true;
        } else {
          $message.createMessage.warning(res.msg);
          handleChangeCheckCode();
          return false;
        }
      });
    } finally {
      return false;
    }
  }

  //表单提交事件
  async function handleSubmit() {
    try {
      const values = await validate();
      setModalProps({ confirmLoading: true });
      //提交表单
      let params = Object.assign({ mobile: unref(values.mobile), captcha: unref(values.captcha) });
      let url = '/api-upms/sys/user/putSysUserMobile/' + params.mobile + '/' + params.captcha;
      defHttp.put({ url: url }, { isTransformResponse: false }).then((res) => {
        if (res.success) {
          $message.createMessage.success('更新成功');
          //关闭弹窗
          closeModal();
          emit('success');
        } else {
          $message.createMessage.warning(res.msg);
          handleChangeCheckCode();
        }
      });
    } finally {
      setModalProps({ confirmLoading: false });
    }
  }

  //初始化验证码
  onMounted(() => {
    handleChangeCheckCode();
  });

  async function show(name) {
    if (!name) {
      $message.createMessage.warning('当前系统无登录用户!');
      return;
    } else {
      await setModalProps({ visible: true });
      await resetFields();
      await clearValidate();
      handleChangeCheckCode();
    }
  }

  defineExpose({
    show,
  });
</script>

<style lang="less" scoped>
  .randcode-btn {
    width: 20%;
  }

  .randcode-input {
    width: 70%;
  }
</style>
